#pragma once
#include <iostream>
#include <functional>
#include <pthread.h>
namespace ThreadModule
{
    using func_t = std::function<void(const std::string&)>;

    class Thread
    {
    public:
        Thread(func_t func, const std::string& name)
            : _func(func), _threadName(name), _stop(true)
        {}
        ~Thread()
        {}
        void Excute()
        {
            _func(_threadName);
        }
        static void* threadrun(void* args)
        {
            Thread* td = static_cast<Thread*>(args);
            td->Excute();
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadrun, this);
            if(!n)
            {
                _stop = false;
                return true;
            }
            else
                return false;
        }
        void Detach()
        {
            if(!_stop)
            {
                pthread_detach(_tid);
            }
        }
        void Join()
        {
            if(!_stop)
            {
                pthread_join(_tid, nullptr);
            }
        }
        void Stop()
        {
            _stop = true;
        }
        std::string name()
        {
            return _threadName;
        }

    private:
        pthread_t _tid;
        func_t _func;
        std::string _threadName;
        bool _stop;
    };
}
